/*
 *  RenderView.cpp
 *  3dModellingKinect
 *
 *  Created by Jeff Nicholson on 11-11-03.
 *  Copyright 2011 University of Calgary. All rights reserved.
 *
 */

#include "RenderView.h"

RenderView::RenderView(MyFreenectDevice* device) : AbstractView() {
	WIDGET_WIDTH = 640;
	WIDGET_HEIGHT = 480;
	
	m_device = device;
}
RenderView::~RenderView() {}

void RenderView::initializeGL()
{
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClearDepth(1.0);
	glDepthFunc(GL_LESS);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glShadeModel(GL_SMOOTH);
	glGenTextures(1, &gl_depth_tex);
	glBindTexture(GL_TEXTURE_2D, gl_depth_tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
}

void RenderView::paintGL()
{
	makeCurrent();
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	//glOrtho (0,640, 480, 0, -1.0f, 1.0f);
	gluPerspective(45.0, 640.0f/480.0f, 0.00001, 500.0);
	glMatrixMode(GL_MODELVIEW);
	
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();	
	gluLookAt(	-5, 0, 0,		// camera position
					0, 0, 0,		// look at 
					0, 1, 0);	// up vector

	//static std::vector<uint8_t> depth(640*480*4);
	static std::vector<float> depth(640*480);

	m_device->updateState();
	m_device->getDepth(depth);
	
	// print out some depth info
	
	/*printf("Depth buff sample\n");
	for(unsigned int i = 0; i < 640; ++i) {
		printf("%f\n", depth[640*240+i]);
	}*/
	

	static float minDistance = -10.0;
	static float scaleFactor = 0.0021;
	static float w = 640, h = 480, z;

	glColor3f(1.0f,0.0f,0.0f);
	
	glPointSize(1.0f);
	glBegin(GL_POINTS);
	for(int i = 0; i < 640; ++i) {
		for(int j = 0; j < 480; ++j) {
			z = depth[i*j];
			if(z > 0.15 && z < 0.3){
	//			glVertex3f( (i-w/2) * (z + minDistance) * scaleFactor * (w/h),
	//							(j-h/2) * (z + minDistance) * scaleFactor, z );
	//	}	
				glVertex3f( i/w*2-1, j/h*(-2)+1, (-1)*z );
			}
		}
	}
	glEnd();
	
	
	/*
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, gl_depth_tex);
	glTexImage2D(GL_TEXTURE_2D, 0, 3, 640, 480, 0, GL_RGB, GL_UNSIGNED_BYTE, &depth[0]);
	
	glBegin(GL_TRIANGLE_FAN);
	glColor4f(255.0f, 255.0f, 255.0f, 255.0f);
	glTexCoord2f(0, 0); glVertex3f(0,0,0);
	glTexCoord2f(1, 0); glVertex3f(640,0,0);
	glTexCoord2f(1, 1); glVertex3f(640,480,0);
	glTexCoord2f(0, 1); glVertex3f(0,480,0);
	glEnd();
	*/
	glFlush();
}


void RenderView::mousePressEvent(QMouseEvent *event) {}

void RenderView::mouseMoveEvent(QMouseEvent *event) {}
